package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.LoginParam;
import com.itheima.service.LoginService;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private EmpMapper empMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoginInfo login(LoginParam loginParam) {

       // Emp emp = loginMapper.selectEmpByUserAndName(loginParam);
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getUsername, loginParam.getUsername());
        queryWrapper.eq(Emp::getPassword, loginParam.getPassword());
        LambdaQueryWrapper<Emp> eq = queryWrapper;
        Emp emp = empMapper.selectOne(eq);

       if(emp ==null){
           return null;
       }

       LoginInfo loginInfo =new LoginInfo();
        loginInfo.setId(emp.getId());
        loginInfo.setUsername(emp.getUsername());
        loginInfo.setName(emp.getName());
        // loginInfo.setToken();

        // 1,生成 token 信息
        HashMap<String,Object> user = new HashMap<>();
        user.put("username",emp.getUsername());
        user.put("name",emp.getName());
        user.put("id",emp.getId());

        String token = JwtUtils.generateJwt(user);

        // 2，设置token 信息
        loginInfo.setToken(token);


        return loginInfo;


    }
}
